<template>
  <div class="page-container">
    <ResponsiveNav />
    <div class="nav-placeholder"></div>

    <div class="home">
      <!-- 轮播图 Banner -->
      <div class="banner-wrapper">
        <Banner />
        <div class="banner-overlay"></div>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 游戏和家居卡片组 （1）-->
        <div class="card-group full-width">
          <!-- 四格卡片 -->
          <div v-for="(v, i) in categoryList" :key="v.id">
            <QuadCard v-if="i % 2 === 0" :title="v.name" :catId="v.catId" :items="v.products" :footerText="$t('了解更多')" />

            <!-- 单图卡片 -->
            <SingleCard v-else :title="v.name" :catId="v.catId" :items="v.products" :footerText="$t('了解更多')" />
          </div>
        </div>



        <!-- 秒杀商品-->
        <div class="a-cardui full-width product-carousel-container">
          <div class="a-cardui-header" style="display: flex;align-items: center">
            <h2 class="headline">{{ $t('秒杀优惠券') }}</h2>
            <el-text size="large" type="danger">{{timeString(productsWSS.beginTime) }} ~ {{ timeString(productsWSS.endTime) }}</el-text>
          </div>
          <ProductCarousel :products="flashsaleproducts" :type="2" class="mt-4" />
        </div>
<!--        <CategoryCarousel />-->
        <!-- 多产品轮播 （1）-->
        <div class="a-cardui full-width product-carousel-container">
          <div class="a-cardui-header">
            <h2 class="headline">{{ $t('热门优惠卷') }}</h2>
          </div>
          <ProductCarousel :products="featuredProducts" :type="1" class="mt-4" />
        </div>

        <!-- 随机商品 （1）-->
        <div class="hot-header">
          <h2 class="headline">{{ $t('优惠券') }}</h2>
        </div>
        <div class="card-group full-width">
          <!-- 四格卡片 -->
          <div v-for="(v, i) in randomProducts" :key="i">
            <QuadCard v-if="i % 2 === 0" :items="v" />

            <!-- 单图卡片 -->
            <SingleCard v-else :items="v" />
          </div>
        </div>
      </div>
    </div>
    <!-- 秒杀商品 -->
<!--    <div>-->
<!--      <el-dialog v-model="dialogTableVisible" @close="closeCick" :title="$t('秒杀活动')" width="80%">-->
<!--        <div class="MSSP">-->
<!--          <p>{{ $t('开始时间') }}:  {{timeString(productsWSS.beginTime) }}</p>-->
<!--          <p>{{ $t('结束时间') }}:  {{ timeString(productsWSS.endTime) }}</p>-->
<!--          <p class="MSSP-button"><el-button size="large" type="success">-->

<!--            <router-link to="/deals"  style="color: #fff;text-decoration: none;">-->
<!--                <i class="fas fa-bolt"></i>-->
<!--              {{ $t('去参与') }}-->
<!--              </router-link>-->
<!--          </el-button></p>-->
<!--        </div>-->
<!--      </el-dialog>-->
<!--    </div>-->
    <div class="bottom-wrapper">
      <PersonalizedRecommendation />
      <Footer />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted ,onBeforeUnmount} from 'vue'
import ResponsiveNav from '@/components/ResponsiveNav.vue'
import Footer from '@/components/Footer.vue'
import { Banner, ProductCarousel, CategoryCarousel } from './components'
import QuadCard from './components/QuadCard.vue'
import SingleCard from './components/SingleCard.vue'
import PersonalizedRecommendation from '@/components/PersonalizedRecommendation.vue'
import useCartStore from "@/store/modules/cart.js";
import { ApiCommodityList ,ApiCommoditySeckillList,getRandomProducts} from "@/api/commodity.js";
import { ElLoading } from "element-plus";
import useLangStore from "@/store/modules/lang.js";
import { getToken, setToken, removeToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore();
const cartStore = useCartStore()
import {useI18n} from "vue-i18n";
const { t } = useI18n();

const categoryList = ref([])
const dialogTableVisible = ref(false)

const featuredProducts = ref([])
const flashsaleproducts = ref([])

const initData = () => {


  const loading = ElLoading.service()
  const promisesArr = []
  const cList = cartStore.fatherCategoryList.filter(v => v.indexShow === 2)
  cList.forEach(v => {
    promisesArr.push(ApiCommodityList({
      pageNum: 1,
      pageSize: 4,
      level1: v.catId,
      type:0,
      // indexShow: 1,
      countryId: useLangStore().languageId
    }))
  })
  Promise.all(promisesArr).then(res => {
    categoryList.value = cList.map((v, i) => {
      return {
        ...v,
        products: res[i].rows
      }
    })
  }).finally(() => {
    loading.close()
  })

  // 获取第一页商品展示
  ApiCommodityList({
    pageNum: 1,
    type:0,
    pageSize: 10,
  }).then(res => {
    featuredProducts.value = res.rows
  })
  ApiCommoditySeckillList({
    level1: '',
    level2: '',
    pageNum: 1,
    pageSize: 10,
  }).then(res => {
    flashsaleproducts.value = res.rows
  })
}

//随机商品
const randomProducts = ref([])
const getRandom = () =>{
  getRandomProducts().then(res => {
    const originalArray = res.data || []
    let result = [];
    let i = 0;
    while (i < originalArray.length) {
      if (originalArray.length - i >= 4) {
        result.push(originalArray.slice(i, i + 4));
        i += 4;
      } else {
        console.log(originalArray.slice(i))
        result.push(originalArray.slice(i));
        break;
      }
      if (i < originalArray.length) {
        result.push([originalArray[i]]);
        i++;
      }
    }
    randomProducts.value = result
  })
}
//开始链接WWS
/*********************************************************** */

const productsWSS = ref(''); // 存储接收到的商品数据
let ws = null; // WebSocket 实例（在 setup 中定义）
// 读取本地弹窗ID
const closeOpenIdKey = ref(sessionStorage.getItem('closeOpenId'));
const closeOpenKey = ref(sessionStorage.getItem('closeOpen'));
// 初始化 WebSocket 连接
const initWebSocket = () => {
  // 替换为你的实际 WSS 地址
  const wsUrl = "wss://h5-api.tw-coinget.com/ws/notice/platform/notice_buyer/"+userStore.userInfo?.member?.id || '';
  ws = new WebSocket(wsUrl);

  // 监听 WebSocket 打开事件
  ws.onopen = () => {
    console.log("WSS 连接成功！");
    // 如果需要，可以在连接建立后发送订阅消息
    ws.send(
      JSON.stringify({ action: "subscribe", topic: "product_updates" })
    );
  };
console.log(getToken(),'getToken');

  // 监听 WebSocket 消息事件
  ws.onmessage = (event) => {
    console.log("接收到消息：", event.data);
    try {
      const data = JSON.parse(event.data);
      // console.log(data.data.type,'data');
      if (data.data?.type == "999") {
        productsWSS.value = data.data;
        sessionStorage.setItem('closeOpenId', data.data.id);

        // if(closeOpenIdKey.value == data.data.id && closeOpenKey.value){
        //   dialogTableVisible.value = false;
        // }else{
        //   dialogTableVisible.value = true;
        // }
      }

    } catch (error) {
      console.error("解析推送数据失败：", error);
    }
  };

  // 监听 WebSocket 关闭事件
  ws.onclose = () => {
    console.log("WSS 连接已关闭");
    console.log("WSS 连接已关闭，尝试重新连接...");
    setTimeout(() => {
      initWebSocket(); // 重连
    }, 3000); // 3秒后重连
    // 如果需要，可以在这里实现重连逻辑

  };

  // 监听 WebSocket 错误事件
  ws.onerror = (error) => {
    console.error("WSS 发生错误：", error);
  };
};
//关闭秒杀弹窗
const closeCick = ()=>{
  // 存储数据
sessionStorage.setItem('closeOpen', true);
}
//时间戳转换
const timeString = (timestamp)=>{
    if(!timestamp){
      return
    }
      // 将时间戳转换为 Date 对象
    const date = new Date(timestamp);

    // 提取年月日时分秒
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要加 1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    // 拼接成字符串
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return formattedDate;
}
// setInterval(() => {
//   if (ws && ws.readyState === WebSocket.OPEN) {
//     ws.send(JSON.stringify({ action: "ping" }));
//   }
// }, 30000); // 每 30 秒发送一次心跳
// 组件挂载后初始化 WebSocket
onMounted(() => {
  initData()
  getRandom()
  initWebSocket();
});

// 组件销毁前关闭 WebSocket
// onBeforeUnmount(() => {
//   if (ws) {
//     ws.close(); // 关闭 WebSocket 连接
//     console.log("WebSocket 已关闭");
//   }
// });


</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  overflow-x: hidden;
}

.nav-placeholder {
  display: none; // 默认隐藏

  @media screen and (min-width: 769px) {
    display: block;
  }
}

.home {
  flex: 1;
  width: 100%;
  max-width: 1500px;
  margin: 0 auto;
  background-color: #F5F5F5;
  position: relative;

  @media screen and (max-width: 768px) {
    margin-top: 0; // 移动端不需要margin-top
  }
}

.banner-wrapper {
  position: relative;
  z-index: 1;

  @media screen and (max-width: 768px) {
    height: 200px; // 移动端降低 banner 高度
    overflow: hidden; // 超出部分隐藏

    :deep(.banner) {
      height: 100%;

      img {
        height: 100%;
        object-fit: cover; // 图片填充方式
        object-position: center; // 图片居中显示
      }
    }
  }
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30%;
  background: linear-gradient(to bottom, transparent, #F5F5F5);
  pointer-events: none;
}

.main-content {
  position: relative;
  z-index: 2;
  margin-top: -360px;
  padding: 20px;

  >.card-group+.card-group {
    margin-top: 0px;
  }

  @media screen and (max-width: 768px) {
    margin-top: -100px;
    padding: 16px;

    >.card-group+.card-group {
      margin-top: 16px;
    }
  }
}

.hot-header{
  margin: 20px 0 10px 20px;
  height: 30px;
  line-height: 30px;
}
.card-group {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 0;

  @media screen and (max-width: 1200px) {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  @media screen and (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}

.full-width {
  grid-column: 1 / -1;
  width: 100%;
  box-sizing: border-box;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: var(--spacing-md);
}

.flash-sale {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: var(--spacing-md);
  background-color: var(--background-light);
  padding: var(--spacing-md);
  border-radius: var(--border-radius-lg);
}

.bottom-wrapper {
  width: 100%;
  background-color: #fff;
  margin-top: auto;
}

.a-cardui {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  height: 100%;

  .a-cardui-header {
    margin-bottom: 16px;

    .headline {
      font-size: 21px;
      line-height: 27.3px;
      font-weight: 700;
      color: #0F1111;
      margin-right: 10px;
    }
  }
}

.product-carousel-container {
  margin-top: 12px;
  padding: 20px;
}
.MSSP{
  p{
    padding: 10px 0;
  }
  .MSSP-button{
    text-align: center;
    margin-top: 30px;

  }
}
</style>
